package com.example.demo.auth.compoent;


import com.example.demo.entity.vo.CaptchVo;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 自定义拦截器，用来做验证码
 */
@Controller
public class MyOncePerRequestFilter extends OncePerRequestFilter
{
//    自定义认证失败处理器
    @Resource
    CustomAuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        /**
         * 拦截登录请求
         */
        if(StringUtils.equals("/login",httpServletRequest.getRequestURI())&&StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(),"POST")){
            try {
                //validate抛出的SessionAuthenticationException可以被捕获
                validate(new ServletWebRequest(httpServletRequest));
            }catch (AuthenticationException e){
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
                return;
            }
        }

        filterChain.doFilter(httpServletRequest,httpServletResponse);

    }
    //验证验证码
    void validate(ServletWebRequest webRequest){
        HttpSession session = webRequest.getRequest().getSession();
        try {
            //获取请求中的验证码
            String codeInRequest = ServletRequestUtils.getStringParameter(webRequest.getRequest(), "capcode");
            if(StringUtils.isEmpty(codeInRequest)){
                throw new SessionAuthenticationException("验证码为空值");
            }
            //获取获取session中的验证码
            CaptchVo captchVo = (CaptchVo)session.getAttribute("cap_key");
            if(captchVo==null){
                throw new SessionAuthenticationException("Session中验证码为空值");
            }
            if(captchVo.isExpired()){
                throw new SessionAuthenticationException("验证码过期刷新重试");
            }
            if(!StringUtils.equals(captchVo.getCode(),codeInRequest)){
                throw new SessionAuthenticationException("验证码输入错误");
            }

        } catch (ServletRequestBindingException e) {
            e.printStackTrace();
        }
    }
}
